<?php


namespace App\Http\Model;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class RoomUserProtect extends Base
{
    protected $table = 'mic_user_protect_level';
    protected $micUserProtectConfig = 'mic_user_protect_config';//守护配置表
    protected $micUserProtectStream = 'mic_user_protect_stream';//用户开通守麦流水记录
    protected $roomStreamTable = 'finance_room_wealth_stream';//房间流水

    protected $roomUsertProtectTypeKey = 'ROOM:USER:PROTECT:';//房间用户守护缓存 string ROOM:USER:PROTECT:{roomId}:{userId}=>{json}
    protected $dayRoomProtectRedisKey = 'ROOM:USER:PROTECT:RANK:DAY:';//房间守护榜日榜
    protected $weekRoomProtectRedisKey = 'ROOM:USER:PROTECT:RANK:WEEK:';//房间守护周榜

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    //获取用户在对应房间下的守护类型
    public function getUserProtectList($roomId, $userId){
        $res = Redis::GET($this->roomUsertProtectTypeKey.$roomId.':'.$userId);
        if(empty($res)){
            $time = date('Y-m-d H:i:s',time());
            $res = DB::table($this->table)->where(['user_id'=>$userId,'room_id'=>$roomId])->where('start_time','<=',$time)->where('end_time','>=',$time)->first();
            $res = self::objToArray($res);
            if(!empty($res)){
                //计算截止时间到现在剩余的秒数
                $now = Carbon::now()->toDateTimeString();
                $selctDate = $res['end_time'];
                $diffTime = Carbon::parse($now)->diffInSeconds($selctDate);
                //记录缓存
                Redis::SET($this->roomUsertProtectTypeKey.$roomId.':'.$userId,json_encode($res));
                Redis::EXPIRE($this->roomUsertProtectTypeKey.$roomId.':'.$userId,$diffTime);
            }
        }else{
            $res = json_decode($res,true);
        }
        $protectArr = DB::table($this->micUserProtectConfig)->get(['id','name','promise','diamond','day']);
        $protectArr = self::objToArray($protectArr);
        //整理数据
        foreach($protectArr as &$v){
            $promise = json_decode($v['promise'],true);
            foreach($promise as &$val){
                $val['icon'] = build_image($val['icon']);
            }
            if(!empty($res)){
                $v['protect_info'] = $res;
            }else{
                $v['protect_info'] = new \stdClass();
            }
            $v['promise'] = $promise;
        }
        return $protectArr;
    }

    //获取房间下守护排名
    public function getRoomProtectRank($roomId, $type, $start_time, $end_time, $page, $limit){
        if($type==1){
            $date = Carbon::now()->toDateString();
            $redisKey = $this->dayRoomProtectRedisKey.$date.':'.$roomId; // 日榜
        }else{
            $weekStart = Carbon::now()->startOfWeek()->toDateString();
            $weekEnd = Carbon::now()->endOfWeek()->toDateString();
            $redisKey = $this->weekRoomProtectRedisKey.$weekStart.'=>'.$weekEnd.':'.$roomId; //周榜
        }
        $pagesize = ($page - 1) * $limit;
        $rank = Redis::zrevrangebyscore($redisKey,'+inf','-inf',['withscores'=>true , 'limit'=>[$pagesize,$limit]]);
        return $rank;
    }

    //获取用户在房间下的守护类型
    public function getUserProtectType($roomId, $userId){
        $res = Redis::GET($this->roomUsertProtectTypeKey.$roomId.':'.$userId);
        if(empty($res)){
            $time = date('Y-m-d H:i:s',time());
            $res = DB::table($this->table)->where(['user_id'=>$userId,'room_id'=>$roomId])->where('start_time','<=',$time)->where('end_time','>=',$time)->first();
            $res = self::objToArray($res);
            if(!empty($res)){
                //计算截止时间到现在剩余的秒数
                $now = Carbon::now()->toDateTimeString();
                $selctDate = $res['end_time'];
                $diffTime = Carbon::parse($now)->diffInSeconds($selctDate);
                //记录缓存
                Redis::SET($this->roomUsertProtectTypeKey.$roomId.':'.$userId,json_encode($res));
                Redis::EXPIRE($this->roomUsertProtectTypeKey.$roomId.':'.$userId,$diffTime);
            }
        }else{
            $res = json_decode($res,true);
        }
        return $res;
    }

    //获取过期的守护信息
    public function getUserPassedProtect($roomId, $userId){
        $time = date('Y-m-d H:i:s',time());
        $res = DB::table($this->table)->where(['user_id'=>$userId,'room_id'=>$roomId])->where('start_time','<=',$time)->where('end_time','<=',$time)->orderBy('id','desc')->first();
        $res = self::objToArray($res);
        return $res;
    }

    //获取服务信息
    public function getProtectInfo($id){
        $protectArr = DB::table($this->micUserProtectConfig)->where('id',$id)->first(['id','name','promise','diamond','day','hour_diamond','gift_id']);
        $protectArr = self::objToArray($protectArr);
        return $protectArr;
    }

    //开通服务处理
    public function insertUserProtect($data){
        //查看是否有未生效的服务,更改起止时间
        $check = DB::table($this->table)
                ->where('user_id',$data['user_id'])
                ->where('room_id',$data['room_id'])
                ->where('protect_type','=', $data['protect_type'])
                ->where('start_time','>=',date('Y-m-d H:i:s',time()))
                ->first();
        $check = self::objToArray($check);
        $getProtectInfo = $this->getProtectInfo($data['protect_type']);
        //重新更改起止
        if(!empty($check)){
            $data = [
                'end_time' => Carbon::parse($check['end_time'])->addDays($getProtectInfo['day'])->toDateTimeString(),
                'updated_at' => Carbon::now()->toDateTimeString() 
            ];
            $res = DB::table($this->table)->where('id',$check['id'])->update($data);
        }else{
            $res = DB::table($this->table)->insert($data);
        }
        return $res;
    }

    //续费服务处理
    public function updateUserProtect($data,$id,$roomId){
        $res = DB::table($this->table)->where('id',$id)->update($data);
        Redis::DEL($this->roomUsertProtectTypeKey.$roomId.':'.$data['user_id']);
        //查看是否有未生效的服务,更改起止时间
        $check = DB::table($this->table)
                ->where('user_id',$data['user_id'])
                ->where('room_id',$data['room_id'])
                ->where('protect_type','!=', $data['protect_type'])
                ->where('start_time','>=',date('Y-m-d H:i:s',time()))
                ->get();
        $check = self::objToArray($check);
        //重新更改起止
        if(!empty($check)){
            foreach($check as $val){
                $start_time = $data['end_time'];
                //查看原来服务间隔天数
                $diffDay = Carbon::parse($val['end_time'])->diffInMinutes($val['start_time']);
                $getProtectInfo = $this->getProtectInfo($val['protect_type']);
                if($diffDay > $getProtectInfo['day']){
                    //说明之前续费过此服务必须额外加上原来的天数
                    $addDay = $getProtectInfo['day'] + $diffDay;
                    $end_time = Carbon::parse($start_time)->addDays($addDay)->toDateTimeString();
                }else{
                    $end_time = Carbon::parse($start_time)->addDays($getProtectInfo['day'])->toDateTimeString();
                }
                $change = [
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'updated_at' => Carbon::now()->toDateTimeString(),
                ];
                DB::table($this->table)->where('id',$val['id'])->update($change);
            }    
        }
        return $res;
    }

    //记录流水服务
    public function insertProtectStream($data){
        $res = DB::table($this->micUserProtectStream)->insert($data);
        return $res;
    }

}